/**
 * 
 */
package com.personal.Visualplan.imp;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.personal.Visualplan.entity.Plan;
import com.personal.Visualplan.repository.PlanRepository;
import com.personal.Visualplan.service.PlanService;

/**
 * <p>
 * Project name:Visualplan
 * </p>
 * <p>
 * Class name:PlanImp
 * </p>
 * 
 * @author "JiHongru"
 * @version
 * @date 2020年3月2日下午5:08:19
 * @description 该类为PlanService接口的实现
 */
@Service
public class PlanImp implements PlanService {

	@Resource
	private PlanRepository planRepository;

	/**
	 * 发布任务
	 * 
	 * @return Plan
	 *
	 */
	public Plan releasePlan(Plan plan) {
		Plan result = planRepository.save(plan);
		if (result != null) {
			return result;
		}
		return null;
	}

	@Override
	public List<Plan> findPlansByStatus(int status, int user_id) {
		List<Plan> plans = new ArrayList<Plan>();
		plans = planRepository.findByStatusAndUser_id(status, user_id);
		return plans;
	}

	@Override
	public Plan findPlanById(int id) {
		return planRepository.findById(id);
	}

	@Override
	public Plan save(Plan plan) {
		return planRepository.save(plan);
	}

	@Override
	public List<Plan> findPlansByUserAndTag(int userId, int tagId, Timestamp startTime, Timestamp endTime) {
		if (startTime == null || endTime == null)
			return null;
		List<Plan> result = new ArrayList<Plan>();// 用于记录筛选后的结果
		List<Plan> plans = new ArrayList<Plan>();
		plans = planRepository.findByTag_idAndUser_id(userId, tagId);
		for (Plan plan : plans) {
			if (plan.getRelease_time().after(startTime) && plan.getRelease_time().before(endTime)) {
				result.add(plan);
			} else if (plan.getEnd_time() != null) {
				if (plan.getEnd_time().after(startTime) && plan.getEnd_time().before(endTime)) {
					result.add(plan);
				}
			}
		}
		return result;
	}

	@Override
	public List<Plan> findPlansByUserAndTag(int userId, int tagId) {
		Calendar todayStart = Calendar.getInstance();
		todayStart.set(Calendar.HOUR_OF_DAY, 0);
		todayStart.set(Calendar.MINUTE, 0);
		todayStart.set(Calendar.SECOND, 0);
		todayStart.set(Calendar.MILLISECOND, 0);
		Timestamp startTime = new Timestamp(todayStart.getTime().getTime());
		Timestamp endTime = new Timestamp(new Date().getTime());
		return findPlansByUserAndTag(userId, tagId, startTime, endTime);
	}
}
